<?php

declare(strict_types=1);


namespace App\CustHub\Controller;

use App\Common\Constants\ErrorCode;
use App\CustHub\Annotation\ApiAuth;
use App\CustHub\Annotation\ChPermission;
use App\CustHub\Annotation\VerifySignature;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Model\ChMaterial;
use App\CustHub\Model\ChMaterialTag;
use App\CustHub\Model\ChMaterialToTag;
use App\CustHub\Model\ChWordGroup;
use App\CustHub\Service\ChMaterialService;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use App\CustHub\Service\ChUserService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Validation\Rule;

#[Controller(prefix: 'ch/material'),ApiAuth,VerifySignature]
class MaterialController extends BaseController
{
    #[Inject]
    protected ChUserService $service;

    #[Inject]
    protected ChRobotMapper $robotMapper;

    #[Inject]
    protected ChMaterialService $chMaterialService;

    /**
     * 添加标签
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('tag/add'),ChPermission('ch:word:tag:add')]
    public function addTag()
    {
        $this -> validateParam([
            'is_personal' => 'required',
            'name' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $isPersonal =$this->request->input('is_personal');
        $mainUid = $this->request->input('main_uid');
        //$materialId =$this->request->input('material_id');
        $name =$this->request->input('name');
        $res = ChMaterialTag::saveTag($uid,$mainUid,$isPersonal,$name);
        return $this -> success('添加成功',$res);
    }

    #[PostMapping('tag/delete'),ChPermission('ch:word:tag:delete')]
    public function deleteTag()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $id =$this->request->input('id');
        Db::transaction(function ()use($id){
            ChMaterialTag::query() -> where('id',$id) -> delete();
            ChMaterialToTag::query() -> where('tag_id',$id) -> delete();
        });
        return $this -> success('删除成功');
    }

    #[PostMapping('tag/list'),ChPermission('ch:word:tag:list')]
    public function tagList()
    {
        $this -> validateParam([
            'is_personal' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $id =$this->request->input('id');
        $mainUid = $this->request->input('main_uid');
        $search = $this->request->input('keyword');
        $isPersonal =$this->request->input('is_personal',0);

        if($isPersonal == 1){
            $where = [
                ['uid', '=', $uid],
                ['is_personal','=',1]
            ];
        }else{
            $where = [
                ['main_uid', '=', $mainUid],
                ['is_personal','=',0]
            ];
        }
        if(!empty($search)){
            $where[] = ['name','like',"%".$search."%"];
        }
        $list = ChMaterialTag::query() -> where($where) -> orderByDesc('id') -> limit(10) ->get(['id','name']);
        return $this -> success('获取成功',$list);
    }


    /**
     * 添加素材
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('add'),ChPermission('ch:word:add')]
    public function add()
    {
        $this -> validateParam([
            'title' => 'required',
            'content' => 'required',
            'is_personal' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $params = $this -> request -> all();
        $mainUid = $this->request->input('main_uid');
        $res = ChMaterial::saveMaterial($uid,$mainUid,$params);
        return $this -> success('保存成功',$res);
    }


    /**
     * 修改素材
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('edit'),ChPermission('ch:word:edit')]
    public function edit()
    {
        $this -> validateParam([
            'title' => 'required',
            'content' => 'required',
            'is_personal' => 'required',
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $id =$this->request->input('id');
        $params = $this -> request -> all();
        $mainUid = $this->request->input('main_uid');

        $res = ChMaterial::saveMaterial($uid,$mainUid,$params,$id);
        return $this -> success('保存成功',$res);
    }


    /**
     * 复制素材
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('copy'),ChPermission('ch:word:copy')]
    public function copy()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $id =$this->request->input('id');
        $mainUid = $this->request->input('main_uid');

        $data = ChMaterial::query() -> where('id',$id) -> first() -> append('tags');
        if(empty($data)){
            return $this -> error('数据不存在',ErrorCode::NOT_ISSET);
        }
        $data = $data -> toArray();
        $data['tags'] =  array_column($data['tags'],'id');
        $res = ChMaterial::saveMaterial($uid,$mainUid,$data);
        return $this -> success('保存成功',$res);
    }


    #[PostMapping('list'),ChPermission('ch:word:list')]
    public function List()
    {
        $this -> validateParam([
            'is_personal' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $isPersonal =$this->request->input('is_personal');
        $page_size =$this->request->input('page_size',15);
        $params = $this -> request -> all();
        $mainUid = $this->request->input('main_uid');


        if($isPersonal == 1){
            $where = [
                ['m.uid','=',$uid],
                ['m.is_personal','=',1]
            ];
        }else{
            $where = [
                ['m.main_uid','=',$mainUid],
                ['m.is_personal','=',0]
            ];
        }
        if(!empty($params['keyword'])){
            $where[] = ['m.title','like',"%".$params['keyword']."%"];
        }
        if(!empty($params['msg_type'])){
            $where[] = ['m.msg_types','like',"%".$params['msg_type']."%"];
        }
        $query = Db::table('ch_material as m')
            -> leftJoin('ch_material_to_tag as tt','m.id','=','tt.material_id')
            -> leftJoin('ch_material_tag as t','t.id','=','tt.tag_id')
            -> select(['m.*',DB::raw('GROUP_CONCAT(t.id) as tag_ids'), DB::raw('GROUP_CONCAT(t.name) as tag_names')])
            -> groupBy('m.id')  // 根据 material 的 id 分组
            -> orderBy('m.id','desc')  // 根据 material 的 id 分组
            -> where($where);
        if(!empty($params['tag_id'])){
            $query -> havingRaw("FIND_IN_SET(?, tag_ids) > 0", [$params['tag_id']]);
        };
        $page = $query -> paginate((int) $page_size);
        foreach ($page as $item){
            $item ->  content =  !empty($item -> content)?json_decode($item -> content,true):[];
            $item ->  robot_info =  !empty($item -> robot_id)?$this->robotMapper->findById($item -> robot_id):null;
        }
        $list = $page -> items();
        $total = $page -> total();
        return $this -> success('获取成功',['list'=>$list,'total'=>$total]);
    }


    #[PostMapping('set_field'),ChPermission('ch:word:set_field')]
    public function setField()
    {
        $this -> validateParam([
            'field' => [
                'required',
                 Rule::in(['is_star']),
            ],
            'value' => 'required|boolean',
            'id' => 'required',
        ]);
        $uid =$this->request->input('uid');
        $id =$this->request->input('id');
        $value =$this->request->input('value');
        $field =$this->request->input('field');
        ChMaterial::query() -> where('id',$id) -> update([$field => $value]);
        return $this -> success('操作成功');
    }

    #[PostMapping('merge'),ChPermission('ch:word:merge')]
    public function merge()
    {
        $this -> validateParam([
            'title' => 'required',
            'content' => 'required',
            'is_personal' => 'required',
            'is_delete' => 'required|between:0,1',
            'ids' => 'required',
        ]);
        $uid =$this->request->input('uid');
        //是否删除原来的素材
        $is_delete =$this->request->input('is_delete',0);
        $ids =$this->request->input('ids');
        $params = $this -> request -> all();
        $mainUid = $this->request->input('main_uid');

        $res = ChMaterial::saveMaterial($uid,$mainUid,$params);
        if($is_delete == 1){
            $idsArray = explode(",",$ids);
            ChMaterial::query() -> whereIn('id',$idsArray) -> delete();
        }
        return $this -> success('保存成功',$res);
    }

    #[PostMapping('delete'),ChPermission('ch:word:delete')]
    public function delete()
    {
        $this -> validateParam([
            'ids' => 'required',
        ]);
        $ids =$this->request->input('ids');
        $uid =$this->request->input('uid');
        $mainUid = $this->request->input('main_uid');
        if(is_string($ids)){
            $ids = explode(",",$ids);
        }
        ChMaterial::query() -> where('main_uid',$mainUid)  -> whereIn('id',$ids) -> delete();
        return $this -> success('删除成功');

    }

    /**
     * 详情
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    #[PostMapping('detail'),ChPermission('ch:word:detail')]
    public function detail()
    {
        $this -> validateParam([
            'id' => 'required',
        ]);
        $id =$this->request->input('id');
        $data = ChMaterial::query()  -> where('id',$id) -> first() -> append('tags');;
        return $this -> success('复制成功',$data);
    }

}